package com.liuugoqing.creator.singleton.question.serializatio;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 通过序列化和反序列化，可以破坏单例模式；
 * 解决方案，在需要单例的类中，编写 readResolve 方法
 * @Author : liugq
 * @Date : 2022/6/28 11:37
 * @See : 参考类
 * @Since： JDK1.8
 * @Version : 1.0
 */
public class SerializationQue {
    @Test
    public void testSerializationQue() throws Exception{
        writeObject2File();
        Singleton singleton = readObjectFromFile();
        Singleton singleton1 = readObjectFromFile();

        System.out.println(singleton +"------------"+ singleton1);
        System.out.println(singleton == singleton1);
    }

    private  Singleton readObjectFromFile() throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\Users\\刘国庆\\Desktop\\test.txt"));
        Singleton object = (Singleton)ois.readObject();
        ois.close();
        return object;
    }


    /**
     * 将对象序列化进文件中
     * @author liugq
     * @date 2022/6/28 11:41
     */
    private void writeObject2File() throws Exception {
        Singleton instance = Singleton.getInstance();

        //将对象序列化
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\刘国庆\\Desktop\\test.txt"));
        oos.writeObject(instance);
        oos.flush();
        oos.close();
    }
}
